package pl.polsl.mmm.projectcomm.util.bluetooth;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Handler;

import java.io.IOException;
import java.util.UUID;

import pl.polsl.mmm.projectcomm.GameActivity;

/**
 * Klasa reprezentuje połączenie klienta,
 * które w oddzielnym wątku próbuje połączyć się z serwerem
 *
 * Created by michal on 28.12.14.
 */
public class ConnectThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;
    private final BluetoothAdapter mBluetoothAdapter;
    private String uuidString = "a3137d00-8eac-11e4-b4a9-0800200c9a66";
    Handler handler;
    Activity activity;
    private static ConnectedThread connectedThread = null;

    public ConnectThread(Activity pActivity, BluetoothAdapter bluetoothAdapter, BluetoothDevice device, Handler pHandler) {
        // Use a temporary object that is later assigned to mmSocket,
        // because mmSocket is final
        BluetoothSocket tmp = null;
        mmDevice = device;
        mBluetoothAdapter = bluetoothAdapter;
        activity = pActivity;
        handler = pHandler;

        // Get a BluetoothSocket to connect with the given BluetoothDevice
        try {
            // MY_UUID is the app's UUID string, also used by the server code
            tmp = device.createRfcommSocketToServiceRecord(UUID.fromString(uuidString));
        } catch (IOException e) { }
        mmSocket = tmp;
    }

    // Wysłanie danych
    public static void write(byte array[]) {
        if (connectedThread != null) {
            connectedThread.write(array);
        }
    }

    public void run() {
        // Cancel discovery because it will slow down the connection
        mBluetoothAdapter.cancelDiscovery();

        try {
            // Connect the device through the socket. This will block
            // until it succeeds or throws an exception
            mmSocket.connect();
        } catch (IOException connectException) {
            // Unable to connect; close the socket and get out
            try {
                mmSocket.close();
            } catch (IOException closeException) { }
            return;
        }

        // Tworzenie wątku połączenia
        connectedThread = new ConnectedThread(mmSocket, handler);

        // nasłuchiwanie
        connectedThread.start();

        // Przekierowanie do ekranu gry
        Intent intent = new Intent(activity, GameActivity.class);
        activity.startActivity(intent);
    }

    /** Will cancel an in-progress connection, and close the socket */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}
